// request.js
const global = getApp().globalData

const request = options => {
  const token = global.token || wx.getStorageSync('token')

  return new Promise((resolve, reject) => {
    const {
      data,
      method
    } = options
    if (data && method !== 'get') {
      options.data = JSON.stringify(data)
    }
    wx.showLoading({
      title: '加载中……',
      mask: true
    })
    wx.getNetworkType({
      success(res) {
        const networkType = res.networkType
        if (networkType == "none") {
          wx.showToast({
            title: '请先连接网络',
            icon: 'none',
            duration: 2000,
            mask: true
          })
          return false
        }
        var headers = {
          'Content-Type': 'application/json;charset=utf-8'
        }
        if (token) {
          headers = {
            'Content-Type': 'application/json;charset=utf-8',
            'X-Auth-Token': token
          }
        }
        var requestTask = wx.request({
          header: headers,
          ...options,
          success: (res) => {
            //console.log('request success', res)
            if (res.data.error_code)
            {
              // reject(res.data)
              wx.showToast({
                title: res.data.error_code||'请求异常',
                icon: 'none',
                duration: 2000,
                mask: true
              })
            }
            else
              resolve(res.data)
          },
          fail: (res) => {
            console.log('request fail', res)
            reject(res.data)
          },
          complete: (res) => {
            wx.hideLoading()
            console.log('request complete', res)
          }
        })
        requestTask.onHeadersReceived((res) => {
          let token = res.header["X-Subject-Token"] || ''
          if (token) {
            global.token = token
            wx.setStorageSync('token', global.token)
            // console.log('onHeadersReceived: ', token)
          }
        })
      }
    })
  })
}
export default request